package cn.edu.buaa.txtReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import util.Global;
import util.TxtDao;

public class MainActivity extends Activity {

    private TextView titleText;
    private ListView list;
    private FileAdapter adapter;
    private List<Map<String, Object>> allValues = new ArrayList<Map<String, Object>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Global.init(this);
        //取得組件
        titleText = (TextView) findViewById(R.id.title_text);
        list = (ListView) findViewById(R.id.list);

        //准备数据，取得SD卡根目录
        File root = Environment.getExternalStorageDirectory();
        loadFileDate(root);

        //加入监听事件，要知道点的是谁，是文件夹还是文件，是文件夹的话还要知道文件夹完整路径，知道完整路径才能建立file，
        //所以还要加两个值dirFlag和fullPath，可以放到map中，adapter中不取就不会显示
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //取得当前操作的数据
                Map<String, Object> map = allValues.get(position);
                //判断所点的的文件还是文件夹
                boolean dirFlag = (boolean) map.get("dirFlag");
                String fullPath = (String) map.get("fullPath");
                File dir = new File(fullPath);
                if (dirFlag) {
                    //是文件夹，先清空原有数据
                    allValues.clear();
                    if (!Environment.getExternalStorageDirectory().getAbsolutePath().equals(fullPath)) {
                        //加入返回上一级的操作行
                        Map<String, Object> parentData = new HashMap<String, Object>();
                        parentData.put("fileName", "返回上一级");
                        parentData.put("extName", "dir_open");
                        parentData.put("dirFlag", true);
                        parentData.put("fullPath", dir.getParent());
                        //保存一个标志
                        parentData.put("flag", "TRUE");
                        //将这一行加入到数据集合中
                        allValues.add(parentData);
                    }
                    //加入新数据
                    loadFileDate(dir);
                    //使用Adapter通知界面ListView，数据已经修改，界面也要同步修改
                    adapter.notifyDataSetChanged();
                } else {
                    TxtDao.insertData(fullPath);
                    Intent in = new Intent(MainActivity.this, DetailActivity.class);
                    in.putExtra("fullPath", fullPath);
                    startActivity(in);
                }
            }
        });
        adapter=new FileAdapter(this,allValues);
        list.setAdapter(adapter);

        //设置长按按钮的监听事件
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                //取得数据
                Map<String, Object> map = allValues.get(position);
                final File f = new File(map.get("fullPath").toString());
                if (f.isFile()) {
                    //弹出确认框
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("确定要删除文件（" + f.getName() + ")吗？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //将SD卡的文件删除
                            if (f.exists()) {
                                f.delete();
                            }
                            //将列表中的数据删除
                            allValues.remove(position);
                            //通知前端界面确认修改数据
                            adapter.notifyDataSetChanged();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    builder.create().show();
                }
                return false;
            }
        });
    }

    //监听用户的按键事件
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //根据keycode判断用户按下了哪个键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //判断当前是否在SD卡根目录，并取得第一行数据
            Map<String, Object> map = allValues.get(0);
            if ("TRUE".equals(map.get("flag"))) {
                //不是根目录，则返回上一级
                list.performItemClick(list.getChildAt(0), 0, list.getChildAt(0).getId());
            } else {
                //是根目录，则进行弹窗提示是否退出
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("确定要退出吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //关闭当前activity
                        finish();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.create().show();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    //该方法用来展示某个目录
    private void loadFileDate(File dir) {
        //列出该目录下的所有文件
        File[] allFiles = dir.listFiles();
        //设置当前位置额提示信息
        titleText.setText("当前位置:" + dir.getAbsolutePath());
        //做判断
        if (allFiles != null) {
            //循环列出文件
            for (int i = 0; i < allFiles.length; i++) {
                File f = allFiles[i];
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("fileName", f.getName());
                map.put("fullPath", f.getAbsolutePath());
                //为返回上一级目录加标识，
                map.put("realParent", "FALSE");
                //判断是文件夹还是文件
                if (f.isDirectory()) {
                    //是文件夹
                    map.put("extName", "dir_close");
                    map.put("dirFlag", true);
                } else {
                    //是文件，则截出扩展名
                    String extName = f.getName().substring(f.getName().lastIndexOf(".") + 1).toLowerCase();
                    map.put("extName", extName);
                    map.put("dirFlag", false);
                }
                if(f.isDirectory() || map.get("extName").toString().equals("txt")) {
                    allValues.add(map);
                }

            }
        }
    }
}
